package com.icesoft.base.admin.listener;


import com.icesoft.base.admin.entity.SysUser;
import com.icesoft.base.admin.service.SysUserService;
import com.icesoft.base.manager.security.config.LoginPropertySetting;
import com.icesoft.base.manager.security.login.phone.PhoneAuthenticationToken;
import com.icesoft.base.manager.service.system.SysUserLoginRecordService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@AllArgsConstructor
@Slf4j
public class SysUserLockAuthenticationEventListener implements ApplicationListener<AbstractAuthenticationFailureEvent> {
    private final SysUserLoginRecordService sysUserLoginRecordService;
    private final SysUserService sysUserService;
    private final LoginPropertySetting loginPropertySetting;

    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        Authentication authentication = event.getAuthentication();
        SysUser sysUser = null;
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            sysUser = sysUserService.findByUsername(authentication.getName());
        }
        if (authentication instanceof PhoneAuthenticationToken) {
            sysUser = sysUserService.findByPhone(authentication.getName());
        }
        int maxLockCount = loginPropertySetting.getMaxLockCount();
        if (sysUser != null && maxLockCount > 0) {
            long preCreateTime = System.currentTimeMillis() - loginPropertySetting.getMaxLockCountTimeMinute() * 60 * 1000L;
            int errorCount = sysUserLoginRecordService.errorCountByUserIdAndGeCreateTime(sysUser.getId(), new Date(preCreateTime));
            if (errorCount > maxLockCount) {
                sysUser.setLocked(true);
                sysUserService.update(sysUser);
                log.info("账号：【{}】已锁定", sysUser.getUsername());
            }
        }
    }
}
